package com.tgpms.web.earlierStage.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.tgpms.util.Common;
import com.tgpms.util.FTPUtil;

@Component
public class UploadFileTimeTask {

	private final Logger log = LoggerFactory.getLogger(UploadFileTimeTask.class);

	//ftp_url
	@Value("${ftpparam.url}")
	private String url;
	@Value("${ftpparam.port}")
	private Integer port;
	@Value("${ftpparam.username}")
	private String username;
	@Value("${ftpparam.password}")
	private String password;
	@Value("${ftpparam.downurl}")
	private String downurl;
	@Value("${ftpparam.filepath3}")
	private String filepath3;
	@Value("${ftpparam.localloadfile}")
	private String localloadfile;

	//定时将服务器本地文件上传到ftp服务器
	@Scheduled(cron = "0 0 */1 * * *")
	public void task(){
		String hour = Common.fromDateFormat("HH");
		log.info("=======定时将本地文件上传到ftp服务器======"+hour);
		if(Integer.parseInt(hour)<=3 || Integer.parseInt(hour)>=23) {
			String time = Common.fromDateFormat("yyyyMMddHHmmssSSS");
			log.info("=======定时将本地文件上传到ftp服务器开始======"+time);
			InputStream in = null;
			//指定存放上传文件的临时目录
			String fileDir = localloadfile;
			File dir = new File(fileDir);
			//判断目录是否存在，不存在则创建目录
			if (!dir.exists()){
				dir.mkdirs();
			}
			File[] files = dir.listFiles();
			if(files!=null) {
				for(int i=0;i<files.length;i++) {
					if(i>20) {
						break;
					}
					try {
						if(files[i].isFile()) {
							String fileName = files[i].getName();
							log.info(time+"当前循环文件名为："+fileName);
							File excelFile = new File(dir.getAbsolutePath()+ File.separator+ fileName);
							in = new FileInputStream(excelFile);
							if(FTPUtil.upload(url, port, username, password, filepath3, in, fileName)) {
								log.info(time+"当前循环文件名为："+fileName+"上传成功！！！");
								if(in!=null) {
									in.close();
								}
								if(excelFile.delete()) {
									log.info(time+"当前循环文件名为："+fileName+"本地删除成功！！！");
								}else {
									log.info(time+"当前循环文件名为："+fileName+"本地删除失败！！！");
								}
							}else {
								log.info(time+"当前循环文件名为："+fileName+"上传失败！！！");
							}
							Thread.sleep(60000);
						}
						else {
							log.info("当前循环不是文件！！！"+time);
						}
					} catch (Exception e) {
						log.info("当前循环文件上传ftp失败"+time);
						log.error(time+"ftp上传错误"+e);
						e.printStackTrace();
						continue;
					}
				}
			}
			log.info("=======定时将本地文件上传到ftp服务器结束======"+time);
		}
	}

}
